import pytest
from sqlalchemy.exc import ArgumentError
from sqlalchemy.ext.asyncio import async_sessionmaker, AsyncSession

from recruit.adapter.database.db import (
    create_async_session_maker,
    create_async_session,
)
from tests.conftest import load_config
from tests.constants import DATABASE_DIR


def test_create_async_session_maker(set_environ: None) -> None:
    db_url = 'test'
    with pytest.raises(ArgumentError):
        create_async_session_maker(db_url)
    assert load_config().get('DB_URI') is not None
    session_maker = create_async_session_maker(load_config().get('DB_URI'))
    assert isinstance(session_maker, async_sessionmaker)


async def test_create_async_session(set_environ: None) -> None:
    session_maker = create_async_session_maker(load_config().get('DB_URI'))
    async_session = create_async_session(session_maker)
    async for session in async_session:
        assert isinstance(session, AsyncSession)
        break


def test_check_migration_file_exists():
    app_dirs = [d.name for d in DATABASE_DIR.iterdir()]
    assert 'migrations' in app_dirs
    alembic_dir = DATABASE_DIR / 'migrations'
    migrations_dirs = [d.name for d in alembic_dir.iterdir()]
    assert 'versions' in migrations_dirs
    version_dir = alembic_dir / 'versions'
    files_in_version_dir = [
        f.name for f in version_dir.iterdir() if (
                f.is_file() and 'init' not in f.name
        )
    ]
    assert len(files_in_version_dir) > 0
